/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json.listeners;

import com.tencent.tendon.convert.json.JsonReader;
import com.tencent.tendon.convert.json.JsonWriter;

/**
 *
 * @author nbzhang
 */
public final class JsonShortArrayListener extends JsonAbstractListener<short[]> {

    private static final JsonShortArrayListener instance = new JsonShortArrayListener();

    private static final JsonShortListener listener = JsonShortListener.getInstance();

    private JsonShortArrayListener() {
    }

    public static JsonShortArrayListener getInstance() {
        return instance;
    }

    @Override
    public short[] convertFrom(final JsonReader in) {
        int size = 0;
        short[] data = new short[8];
        in.checkArray();
        while (in.hasNext()) {
            if (size >= data.length) {
                short[] newdata = new short[data.length + 4];
                System.arraycopy(data, 0, newdata, 0, size);
                data = newdata;
            }
            data[size++] = listener.convertShortFrom(in);
        }
        short[] newdata = new short[size];
        System.arraycopy(data, 0, newdata, 0, size);
        return newdata;
    }

    @Override
    public final void convertTo(final JsonWriter out, final short[] value) {
        short[] values = value;
        if (values == null) {
            out.writeNull();
            return;
        }
        if (values.length == 0) {
            out.write('[', ']');
            return;
        }

        out.write('[');
        boolean first = true;
        for (short v : values) {
            if (!first) out.write(',');
            listener.convertShortTo(out, v);
            if (first) first = false;
        }
        out.write(']');
    }

    @Override
    public Class<short[]> getType() {
        return short[].class;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}
